﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Com.AMap.Api.Maps;
using Com.AMap.Api.Maps.Model;
using System.Windows.Media;
using Com.AMap.Api.Services.Results;
using Com.AMap.Api.Services;

namespace jbgswin
{
    public partial class chakan : PhoneApplicationPage
    {
        AMap amap;
        AMapGeolocator mylocation;
        AMapMarker marker;
        public static LatLng s;
        public static LatLng go;
        //圆
        private static string rds;
       // private string qid;
        AMapCircle circle;
     //   private static bool lk = true;
      /// <summary>
      /// 
      /// </summary>
 // private  Monitor ms = new Monitor();
      /*  private Mutex ma = new Mutex();
        private Mutex ms = new Mutex();*/
        public chakan()
        {
            InitializeComponent();
            rds = "3000";
            this.ContentPanel.Children.Add(amap = new AMap());
            amap.Loaded += amap_Loaded;
          //  amap.Tap += amap_Tap;
        }
        void amap_Loaded(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();]
            amap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(new LatLng(29.868038, 121.550331), 15));
            this.Dispatcher.BeginInvoke(() =>
            {
                //设置默认的地图经纬度和缩放级别
              //  amap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(new LatLng(39.987326, 116.48236), 13));
                foreach (dituwz g in App.toimport.ToList())
                {
                    ////实例化标注点
                    AMapMarkerOptions opt = new AMapMarkerOptions()
                    {
                        Position = new LatLng(Convert.ToDouble(g.ly),Convert.ToDouble( g.lx)),
                        Title =string.IsNullOrEmpty(g.name)? "empty" :g.name.ToString(),
                        IconUri = new Uri("Images/AZURE.png", UriKind.Relative),
                        //Anchor = new Point(0.5, 1),//图标中心点

                        Snippet = string.IsNullOrEmpty(g.shuoming) ? "empty" : g.shuoming.ToString(),
                        
                        
                    };

                    //添加点
                 AMapMarker   markerc = amap.AddMarker(opt);
            
                    amap.MarkerClickListener += amap_MarkerClickListener;
                }
            });
        }
        void amap_MarkerClickListener(object sender, AMapEventArgs e)
        {
          //  MessageBox.Show(sender.GetType().ToString());
            //显示化弹出信息
            AMapMarker k = sender as AMapMarker;

            AInfoWindow info = new AInfoWindow();
            info.Title = k.Title.ToString();
            info.ContentText = k.Snippet.ToString();
            k.ShowInfoWindow(info, new Point(0, 0));
            go = k.Position;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
           //
            amap.Clear(); 
          //  startgeo();
        }

        private void startgeo()
        {
         // ms.Reset();
            mylocation = new AMapGeolocator();
            mylocation.Start();
            //触发位置改变事件
            mylocation.PositionChanged += mylocation_PositionChanged;
             
        }

        void mylocation_PositionChanged(AMapGeolocator sender, AMapPositionChangedEventArgs args)
        {
 //ms.WaitOne();
            s = args.LngLat;

            this.Dispatcher.BeginInvoke(() =>
            {
                //GeoSearch(args.LngLat);

                /*if (marker == null)
                {*/
              //  marker = new AMapMarker();
                    //添加圆
                    circle = amap.AddCircle(new AMapCircleOptions()
                    {
                        Center = args.LngLat,//圆点位置
                       // Radius = (float)args.Accuracy,//半径
                        Radius = (float)Convert.ToDouble(rds),
                        FillColor = Color.FromArgb(80, 100, 150, 255),
                        StrokeWidth = 2,//边框粗细
                        StrokeColor = Color.FromArgb(80, 0, 0, 255),//边框颜色

                    });

                    //添加点标注，用于标注地图上的点
                    marker = amap.AddMarker(
                   new AMapMarkerOptions()
                   {
                       Position = args.LngLat,//图标的位置
                       Title = "我的位置",
                       Snippet = args.LngLat.ToString(),
                       IconUri = new Uri("Images/marker_gps_no_sharing.png", UriKind.Relative),//图标的URL
                       Anchor = new Point(0.5, 0.5),//图标中心点

                   });
               /* }
                else
                {
                    //点标注和圆的位置在当前经纬度
                    marker.Position = args.LngLat;
                    circle.Center = args.LngLat;
                   // circle.Radius = (float)args.Accuracy;//圆半径
                    circle.Radius = (float) Convert.ToDouble(rds);
                }*/

                //设置当前地图的经纬度和缩放级别
                amap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(args.LngLat, 15));
                /* Debug.WriteLine("定位精度：" + args.Accuracy + "米");
                 Debug.WriteLine("定位经纬度：" + args.LngLat);*/
              //  ms.ReleaseMutex();
             //  ms.
              //  Monitor.Exit(lk);
               // lk = true;
            });
            List<dituwz> dzgo = App.toimport.Where(
                       g =>
                           AMapUtils.CalculateLineDistance(
                               (new LatLng(Convert.ToDouble(g.ly), Convert.ToDouble(g.lx))), s) <
                           (float)Convert.ToDouble(rds)).ToList();
            this.Dispatcher.BeginInvoke(() =>
            {
                //设置默认的地图经纬度和缩放级别
                //  amap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(new LatLng(39.987326, 116.48236), 13));
                foreach (dituwz g in dzgo.ToList())
                {
                    ////实例化标注点
                    AMapMarkerOptions opt = new AMapMarkerOptions()
                    {
                        Position = new LatLng(Convert.ToDouble(g.ly), Convert.ToDouble(g.lx)),
                        Title = string.IsNullOrEmpty(g.name) ? "empty" : g.name.ToString(),
                        IconUri = new Uri("Images/AZURE.png", UriKind.Relative),
                        //Anchor = new Point(0.5, 1),//图标中心点

                        Snippet = string.IsNullOrEmpty(g.shuoming) ? "empty" : g.shuoming.ToString(),


                    };

                    //添加点
                    AMapMarker markerc = amap.AddMarker(opt);

                    amap.MarkerClickListener += amap_MarkerClickListener;
                }
            });
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
          //  ma.WaitOne();
            amap.Clear();
            // Button_Click(null, null);
          //  ms.WaitOne();
             startgeo();
           /* if (lk == true)
            {
                lk = false;
                
            }*/
           /*  ms.WaitOne(20000);
                // 
                   ms.WaitOne();*/
                // Monitor.Enter(lk);
                //   lock (lk)
                /*if (lk == true)
                {*/
                   
                    //  ms.ReleaseMutex();
                 //   Monitor.Exit(lk);
//ma.ReleaseMutex();
                }
            

            private
            void r1_Checked(object sender, RoutedEventArgs e)
        {
            rds = r1.Tag.ToString();
        }

        private void r2_Checked(object sender, RoutedEventArgs e)
        {
            rds = r2.Tag.ToString();
        }

        private void r3_Checked(object sender, RoutedEventArgs e)
        {
            rds = r3.Tag.ToString();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            GetNavigationDriving(s, go);
        }
        private async void GetNavigationDriving(LatLng start, LatLng end)
        {
            //116.481028, 39.989643, 116.465302, 40.004717
            AMapRouteResults rts = await AMapNavigationSearch.DrivingNavigation(start.longitude, start.latitude, end.longitude, end.latitude, Extensions.All);
            if (rts.Erro == null)
            {
                if (rts.Count == 0)
                {
                    MessageBox.Show("无查询结果");
                    return;
                }

                AMapRoute route = rts.Route;
                List<AMapPath> paths = route.Paths.ToList();

                List<LatLng> lnglats = new List<LatLng>();
                foreach (AMapPath item in paths)
                {
                    /*Debug.WriteLine("起点终点距离:" + item.Distance);
                    Debug.WriteLine("预计耗时:" + item.Duration / 60 + "分钟");
                    Debug.WriteLine("导航策略:" + item.Strategy);*/

                    //绘制驾车路线
                    List<AMapStep> steps = item.Steps.ToList();
                    foreach (AMapStep st in steps)
                    {
                      //  Debug.WriteLine(st.Instruction);
                        //Debug.WriteLine(st.Road);
                        // Debug.WriteLine(st.Assistant_action);

                        amap.AddMarker(new AMapMarkerOptions()
                        {
                            Position = latLagsFromString(st.Polyline).FirstOrDefault(),
                            Title = "",
                            Snippet = "Snippet",
                            IconUri = new Uri("Images/car.png", UriKind.Relative),
                        });

                        lnglats = latLagsFromString(st.Polyline);
                        amap.AddPolyline(new AMapPolylineOptions()
                        {
                            Points = latLagsFromString(st.Polyline),
                            Color = Colors.Green,
                            Width = 4,
                        });

                    }

                }
            }
            else
            {
                MessageBox.Show(rts.Erro.Message);
            }

        }
        private List<LatLng> latLagsFromString(string polyline)
        {
            List<LatLng> latlng = new List<LatLng>();

            string[] arrystring = polyline.Split(new char[] { ';' });
            foreach (String str in arrystring)
            {
                String[] lnglatds = str.Split(new char[] { ',' });
                latlng.Add(new LatLng(Double.Parse(lnglatds[1]), Double.Parse(lnglatds[0])));
            }
            return latlng;

        }
    }
}